package com.mjgy.service.impl;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import javax.persistence.EntityManager;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.common.utils.PageUtils;
import com.common.utils.Query;
import com.common.utils.R;
import com.mjgy.entity.MUserEntity;
import com.mjgy.entity.MessageEntity;
import com.mjgy.entity.UserAccessEntity;
import com.mjgy.entity.UserDefriendEntity;
import com.mjgy.entity.UserEvaluateEntity;
import com.mjgy.entity.UserFollowEntity;
import com.mjgy.repository.MessageRepository;
import com.mjgy.repository.RelationshipRepository;
import com.mjgy.service.RelationshipService;

/**
* @Description: TODO
* @author Administrator
* @date 2018年9月14日
* @version V1.0
*/
@Service("/relationshipService")
@Transactional
public class RelationshipServiceImpl implements RelationshipService {

	@Autowired
	private EntityManager em;
	
	@Autowired
	private RelationshipRepository rr;
	@Autowired
	private MessageRepository messageRepository;
	
	@Override
	public R follow(Long activeId, Long passiveId, boolean follow) {
		UserFollowEntity re = rr.findOneByActiveIdAndPassiveId(activeId, passiveId);
		if(re == null) {
			// 新增一条关注记录
			re = new UserFollowEntity();
			re.setActiveId(activeId);
			re.setPassiveId(passiveId);
			re.setFollow(follow);
			re.setCreateTime(new Date());
			em.persist(re);
		} else {
			re.setFollow(follow);
			re.setUpdateTime(new Date());
			em.merge(re);
		}
		
		return R.success();
	}

	@Override
	public R defriend(Long activeId, Long passiveId, boolean defriend) {
		UserDefriendEntity ud = rr.findDefriendByActiveIdAndPassiveId(activeId, passiveId);
		if(ud == null) {
			// 新增一条拉黑记录
			ud = new UserDefriendEntity();
			ud.setActiveId(activeId);
			ud.setPassiveId(passiveId);
			ud.setDefriend(defriend);
			ud.setCreateTime(new Date());
			em.persist(ud);
		} else {
			ud.setDefriend(defriend);
			ud.setUpdateTime(new Date());
			em.merge(ud);
		}
		
		return R.success();
	}

	@Override
	public R followList(Long userId) {
		List<BigInteger> followList = rr.getFollowList(userId);
		
		List<MUserEntity> data = new ArrayList<>();
		for(BigInteger passiveId : followList) {
			// 过滤不存在的被关注人
			if(passiveId == null || passiveId.longValue() == 0) {
				continue;
			}
			MUserEntity passiveUser = em.find(MUserEntity.class, Long.valueOf(passiveId.longValue()));
			// 过滤被删除的用户
			if(passiveUser == null) {
				continue;
			}
			data.add(passiveUser);
		}
		
		return R.success().put("data", data);
	}

	@Override
	public R defriendList(Long userId) {
		List<BigInteger> defriendList = rr.getDefriendList(userId);

		List<MUserEntity> data = new ArrayList<>();
		for(BigInteger passiveId : defriendList) {
			// 过滤不存在的被关注人
			if(passiveId == null || passiveId.longValue() == 0) {
				continue;
			}
			MUserEntity passiveUser = em.find(MUserEntity.class, Long.valueOf(passiveId.longValue()));
			// 过滤被删除的用户
			if(passiveUser == null) {
				continue;
			}
			data.add(passiveUser);
		}
		
		return R.success().put("data", data);
	}

	@Override
	public R access(Long activeId, Long passiveId) {
		// 如果你已经被对方拉黑，则不能继续访问
		UserDefriendEntity defriend = rr.findDefriendByActiveIdAndPassiveId(passiveId, activeId);
		if(defriend != null && defriend.isDefriend()) {
			return R.error(202, "你已被该用户拉黑");
		}
		
		UserAccessEntity access = rr.findAccessByActiveIdAndPassiveId(activeId, passiveId);
		Date curDate = new Date();
		if(access == null) {
			access = new UserAccessEntity();
			access.setActiveId(activeId);
			access.setPassiveId(passiveId);
			access.setCreateTime(curDate);
			access.setUpdateTime(curDate);
			em.persist(access);
		} else {
			access.setUpdateTime(curDate);
			em.merge(access);
		}
		
		return R.success();
	}

	@Override
	public R accessList(Long userId) {
		List<BigInteger> accessList = rr.getAccessList(userId);
		
		List<MUserEntity> data = new ArrayList<>();
		for(BigInteger activeId : accessList) {
			if(activeId == null || activeId.longValue() == 0) {
				continue;
			}
			
			MUserEntity activeUser = em.find(MUserEntity.class, Long.valueOf(activeId.longValue()));
			if(activeUser == null) {
				continue;
			}
			data.add(activeUser);
		}
		return R.success().put("data", data);
	}

	@Override
	public R evaluate(Long activeId, Long passiveId, String content) {
		UserEvaluateEntity ue = rr.findEvaluateByActiveIdAndPassiveId(activeId, passiveId);
		if(ue == null) {
			ue = new UserEvaluateEntity();
			ue.setActiveId(activeId);
			ue.setPassiveId(passiveId);
			ue.setContent(content);
			ue.setCreateTime(new Date());
			em.persist(ue);
		} else {
			ue.setContent(content);
			ue.setUpdateTime(new Date());
			em.merge(ue);
		}
		
		//发消息
		MessageEntity messageEntity = new MessageEntity();
		messageEntity.setIsChecked(0);
		messageEntity.setType("3");
		messageEntity.setSenderId(activeId);
		messageEntity.setUserId(passiveId);
		messageEntity.setSendTime(new Date());
		messageEntity.setContent("对你做出了一个评价");
		messageRepository.save(messageEntity);
		
		return R.success();
	}

	@Override
	public R evaluateList(Long userId) {
		List<UserEvaluateEntity> ueList = rr.findEvaluateByPassivaId(userId);
		List<String> contentList = new ArrayList<>();
		for(UserEvaluateEntity ue : ueList) {
			String content = ue.getContent();
			String[] contents = content.split(",");
			for(String str : contents) {
				contentList.add(str);
			}
		}
		
		// 统计重复评价和个数
		Map<String, Integer> map = new TreeMap<String, Integer>();
		for(int i = 0; i < contentList.size(); i++) {
			String content = contentList.get(i);
			if(map.get(content) == null || map.get(content).intValue() <= 0) {
				map.put(content, 1);
			} else {
				map.put(content, map.get(content) + 1);
			}
		}
		
		return R.success().put("data", map);
	}

	@Override
	public R evaluateContent(Long activeId, Long passiveId) {
		UserEvaluateEntity ue = rr.findEvaluateByActiveIdAndPassiveId(activeId, passiveId);
		if(ue != null) {
			return R.success().put("data", ue.getContent());
		}
		return R.error(202, "没有评价内容");
	}

	@Override
	public PageUtils queryEvaluatePage(Query query) {
		StringBuilder sql = new StringBuilder();
		sql.append("select au.username as ausername \n");
		sql.append("      ,au.nickname as anickname\n");
		sql.append("      ,eva.passive_id \n");
		sql.append("      ,eva.content as content\n");
		sql.append("      ,eva.create_time as create_time \n");
		sql.append("from e_user_evaluate eva \n");
		sql.append("join e_user au on au.id = eva.active_id \n");
		sql.append("where au.sex = :sex \n");
		if(StringUtils.isNotBlank((String) query.get("nickname"))) {
			sql.append("and au.nickname like concat('%', concat(:nickname, '%')) \n");
		}
		if(StringUtils.isNotBlank((String) query.get("content"))) {
			sql.append("and eva.content like concat('%', concat(:content, '%')) \n");
		}
		sql.append("order by eva.create_time desc \n");
		javax.persistence.Query allQy = em.createNativeQuery(sql.toString());
		allQy.setParameter("sex", query.get("sex"));
		if(StringUtils.isNotBlank((String) query.get("nickname"))) {
			allQy.setParameter("nickname", query.get("nickname"));
		}
		if(StringUtils.isNotBlank((String) query.get("content"))) {
			allQy.setParameter("content", query.get("content"));
		}
		List allResult = allQy.getResultList();
		
		sql.append("limit :page, :size \n");
		
		javax.persistence.Query qy = em.createNativeQuery(sql.toString());
		qy.setParameter("sex", query.get("sex"));
		if(StringUtils.isNotBlank((String) query.get("nickname"))) {
			qy.setParameter("nickname", query.get("nickname"));
		}
		if(StringUtils.isNotBlank((String) query.get("content"))) {
			qy.setParameter("content", query.get("content"));
		}
		qy.setParameter("page", query.get("offset"));
		qy.setParameter("size", query.get("limit"));
		List resultList = qy.getResultList();
		
		List<Map<String, Object>> list = new ArrayList<>();
		for(Object row : resultList) {
			Object[] cells = (Object[]) row;
			Map<String, Object> map = new HashMap<>();
			map.put("auUsername", cells[0]);
			map.put("auNickname", cells[1]);
			BigInteger passiveId = (BigInteger) cells[2];
			MUserEntity user = em.find(MUserEntity.class, passiveId.longValue());
			if(user != null) {
				map.put("puUsername", user.getUsername());
				map.put("puNickname", user.getNickname());
			}
			map.put("content", cells[3]);
			map.put("createTime", cells[4]);
			list.add(map);
		}
		
		PageUtils pageUtil = new PageUtils(list, allResult.size(), query.getLimit(), query.getPage());
		return pageUtil;
	}
}
